package com.daveclay.boilermaker.web

import javax.servlet.{ServletContext, ServletContextEvent, ServletContextListener}
import org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap

import org.jboss.resteasy.spi.Registry
import org.jboss.resteasy.spi.ResteasyProviderFactory
import resteasy.ModuleProcessor
import com.daveclay.boilermaker.BoilermakerModule
import org.slf4j.LoggerFactory

class GuiceStartupListener extends ResteasyBootstrap with ServletContextListener with InitParamLookup {

    var logger = LoggerFactory.getLogger(classOf[GuiceStartupListener])
    var servletContextOpt: Option[ServletContext] = None

    override def contextDestroyed(servletContextEvent: ServletContextEvent) {}

    override def contextInitialized(servletContextEvent: ServletContextEvent) {
        servletContextOpt = Some(servletContextEvent.getServletContext)
        super.contextInitialized(servletContextEvent)

        // Note: copied from GuiceResteasyBootstrapServletContextListener
        val context = servletContextOpt.get
        val registry = context.getAttribute(classOf[Registry].getName).asInstanceOf[Registry]
        val providerFactory = context.getAttribute(classOf[ResteasyProviderFactory].getName).asInstanceOf[ResteasyProviderFactory]
        val processor = new ModuleProcessor(registry, providerFactory)

        val module = new BoilermakerModule(this)

        // Note: using our ModuleProcessor to get the Injector instance as a return value
        val injector = processor.process(module)
    }

    override def getInitParameter(name: String) = {
        servletContextOpt match {
            case servletContext: Some[ServletContext] => servletContext.get.getInitParameter("content.dir")
            case None => throw new IllegalStateException("No ServletContext available yet!")
        }
    }
}
